'use strict';

const Service = require('egg').Service;

class ArticleService extends Service {
    /**
     * 查询文章
     *
     * @param {String} id @default null -文章id 传入此值后传入的其他值将失效 翻页参数将指向收藏者列表
     * @param {String} title @default null -文章名称
     * @param {String} content @default null -文章内容
     * @param {String} desc @default null -文章简介
     * @param {String} tag @default null -文章类别
     * @param {Boolean} top @default null -是否置顶
     * @param {Boolean} state @default null -文章状态
     * @param {Number} page @default 1 -当前页
     * @param {Number} currentPage @default 10 -返回条数
     * @param {String} select @default null -要显示的key
     */
    async find({ id, title = '', top = null, state = null, tag = [], sort = -1, page = 1, currentPage = 10 } = {}, select = null) {
        const { ctx } = this;
        const userpopulate = 'title headImg role username';

        if (id) {
            let res = await ctx.model.Article
                .findById(id)
                .populate('auth', userpopulate)
                .populate('tag', 'name')
                .populate({
                    path: 'likesUser',
                    select: userpopulate,
                    options: { skip: page - 1, limit: currentPage }
                })
                .select(select + ' next prev');

            try {
                const next = await ctx.model.Article
                    .find()
                    .where('_id')
                    .sort({ createAt: -1 })
                    .lt(id)
                    .limit(1);

                res.next = {
                    title: next[0].title,
                    _id: next[0]._id
                };
            } catch (e) {

            }
            try {
                const prev = await ctx.model.Article
                    .find()
                    .where('_id')
                    .gt(id)
                    .limit(1)

                res.prev = {
                    title: prev[0].title,
                    _id: prev[0]._id
                };
            } catch (e) {

            }

            if (!res || res.delete) {
                ctx.throw(404, '文章不存在或已被删除');
            }
            // 判断是否收藏
            let userisLike = [];

            if (ctx.state.user) {
                userisLike = await ctx.model.Article.find({ _id: id, likesUser: ctx.state.user._id });
            }
            if (userisLike.length > 0) {
                res.isLike = true;
            }

            return res;
        } else {
            let querys = { delete: false, };
            if (top) {
                querys.top = top
            }
            if (state) {
                querys.state = state
            }
            if (tag.length > 0) {
                querys.tag = { $in: tag }
            }
            const res = await ctx.model.Article
                .find(querys)
                .regex('title', title)
                .sort({ createAt: sort })
                .skip((Number(page) - 1) * Number(currentPage))
                .limit(Number(currentPage))
                .populate('auth', userpopulate)
                .populate('tag', 'name')
                .select(select);
            const count = await ctx.model.Article.find(querys).regex('title', title).count();
            return {
                count,
                page,
                list: res
            };
        }
    }

    /**
     * 新增文章
     *
     * @param {String} title -文章
     * @param {String} content -文章内容
     * @param {Array} tag -文章标签id列表 必须是数组
     * @param {String} top @default false -是否置顶文章
     * @param {String} tagtext @default [] -文章的小标签用于seo
     */
    async create({ title, content, tag = [], desc = '', tagtext = [], top = false } = {}) {
        const { ctx, app } = this;
        if (!tag || tag.length === 0) {
            tag = [app.custom.defaultTag.id];
        }
        const res = await ctx.model.Article.create({
            title,
            content,
            desc,
            tagtext,
            auth: ctx.state.user._id,
            tag,
            top
        });
        console.log(res);
        return res;
    }

    /**
     * 修改/删除文章
     *
     * @param {String} id -文章id
     * @param {Object} payload -修改条件
     */
    async update(id, payload = {}) {
        const { ctx } = this;
        const article = await ctx.model.Article.findById(id);
        if (!article || article.delete) {
            ctx.throw(404, '文章不存在或已被删除');
        }
        // 权限验证
        await ctx.powerValidate(article.auth._id);

        payload.updateAt = Date.now();
        return await ctx.model.Article.findByIdAndUpdate(id, payload);
    }

    /**
     * 收藏/取消收藏文章
     *
     * @param {String} articleTd -文章id
     * @param {String} userId -用户Id
     */
    async userLikeArticle(id) {
        const { ctx } = this;
        const article = await ctx.model.Article.findById(id);

        if (!article) {
            ctx.throw(404, '文章不存在');
        }
        const articleUser = await ctx.model.Article.find({ _id: id, likesUser: ctx.state.user._id });
        console.log(articleUser);
        // 文章中存在此用户
        if (articleUser.length !== 0) {
            await ctx.model.Article.findByIdAndUpdate(id, {
                $pull: { likesUser: ctx.state.user._id },
                $inc: { 'numbers.like': -1 }
            });
            return {
                message: '取消收藏成功',
                action: 'down'
            };
        } else {
            await ctx.model.Article.findByIdAndUpdate(id, {
                $addToSet: { likesUser: ctx.state.user._id },
                $inc: { 'numbers.like': 1 }
            });
            return {
                message: '收藏成功',
                action: 'up'
            };
        }
    }
}

module.exports = ArticleService;
